package push_modules

import (
	"context"
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/db/mongodb/model/wechat"
	es "hft/e"
	"hft/global"
	wapi "hft/tools/weixin/api"
	"hft/tools/weixin/model"
	"html"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// 总推送
type EventPush struct{}

func (e *EventPush) TotalPusher(c *gin.Context) {
	var pushBody model.ScanQrCodeWidthParams
	c.ShouldBindBodyWith(&pushBody, binding.XML) //多次绑定
	switch pushBody.Event {
	case "subscribe": //关注
		// 回复关注消息
		pusher, err := e.SubscribeReply(c, pushBody.BasePush)
		if err != nil {
			fmt.Println("222", err.Error())
			return
		}
		c.XML(200, pusher)
		if pushBody.EventKey != "" {
			// 为关注的扫码行为
			status, err := e.ScanQRCode(pushBody)
			if err != nil {
				fmt.Println(111, err)
				return
			} else if status == "status" {
				c.String(200, "success")
			} else {
				return
			}
		}
	case "CLICK":
		// 自定义菜单
		// 找到对应的key值
		var menuBody model.CustomMenuEvent
		c.ShouldBindBodyWith(&menuBody, binding.XML)
		data, status, err := e.CustomMenu(menuBody)
		if err != nil {
			return
		}
		if status == "noSend" {
			return
		}
		c.XML(200, data)
		break

	}
}

// 关注时回复
func (e *EventPush) SubscribeReply(c *gin.Context, base model.BasePush) (res *model.Reply, err error) {
	var filter = bson.D{{Key: "tag", Value: "subscribe"}}
	var data *wechat.SubscribeReply
	err = global.OC_MON.Database("wechat").Collection("subscribe_reply").FindOne(context.TODO(), filter).Decode(&data)
	if err == mongo.ErrNoDocuments {
		fmt.Println("mongo错误", err.Error())
		return nil, err
	}
	var newRes = &model.Reply{BasePush: base}
	switch data.MsgType {
	case "text":
		newRes.Content = data.Content
	case "image":
		newRes.Image = model.ImageRe{MediaId: data.Image.MediaId}
	case "video":
		newRes.Video = model.VideoRe{Title: data.Video.Title, Description: data.Video.Description, MediaId: data.Video.MediaId}
	case "voice":
		newRes.Voice = model.VoiceRe{MediaId: data.Voice.MediaId}
	case "news":
		newRes.ArticleCount = data.ArticleCount
		// var list []model.ItemRe
	}
	newRes.MsgType = data.MsgType
	var user = newRes.FromUserName
	newRes.FromUserName = newRes.ToUserName
	newRes.ToUserName = user
	return newRes, nil
}

// 处理扫码后的事件
func (e *EventPush) ScanQRCode(data model.ScanQrCodeWidthParams) (status string, err error) {
	// 解析key
	var phone = strings.Split(data.EventKey, "qrscene_")[1]
	// 找出用户
	var account *admin.Account
	err = global.OC_DB.Where("phone = ?", phone).First(&account).Error
	if err != nil {
		fmt.Println(err)
		return "error", errors.New(es.AccountNotExist)
	}
	if account.OpenId == "" {
		if err = global.OC_DB.Where("open_id = ?", data.FromUserName).First(&admin.Account{}).Error; err == nil {
			return "error", errors.New("该open_id已注册")
		}
		// 换取union_id
		fmt.Println("1", data.FromUserName, data.ToUserName)
		union_id, err := wapi.WeiXinUnion.GetUnionID(data.FromUserName)
		fmt.Println("union_id", union_id, err)
		if err != nil {
			return "error", errors.New(es.ErrorInfo)
		}
		// 还未绑定openid
		res := global.OC_DB.Model(&admin.Account{}).Where("id = ?", account.ID).Updates(map[string]interface{}{
			"open_id": data.FromUserName,
			"unionid": union_id,
		})
		if res.Error != nil {
			return "error", errors.New(es.ErrorInfo)
		}
		if res.RowsAffected == 0 {
			return "error", errors.New(es.AccountNotExist)
		}
		return "success", nil
	}

	return "done", nil

}

// 自定义菜单
func (e *EventPush) CustomMenu(menuBody model.CustomMenuEvent) (data *model.Reply, status string, err error) {
	if menuBody.EventKey == "" {
		// 时间不存在
		return nil, "noSend", nil
	} else {
		// 找出key
		var button wechat.Button
		var filter = bson.D{{Key: "key", Value: menuBody.EventKey}}
		err := global.OC_MON.Database("wechat").Collection("wechat_menu").FindOne(context.TODO(), filter).Decode(&button)
		if err != nil {
			return nil, "noSend", err
		}
		var reply = &model.Reply{
			BasePush: model.BasePush{
				FromUserName: menuBody.ToUserName,
				ToUserName:   menuBody.FromUserName,
				CreateTime:   int(time.Now().Unix()),
			},
		}
		if button.Message != "" {
			// 回复文字
			reply.BasePush.MsgType = "text"
			reply.Content = html.UnescapeString(button.Message)
			return reply, "send", nil
		} else if button.MediaID != "" {
			reply.BasePush.MsgType = "image"
			reply.Image.MediaId = button.MediaID
		} else {
			return nil, "noSend", nil
		}
		return reply, "send", nil
	}
}

var EventPushWx = new(EventPush)
